package com.firebird.app.kotlin.stock.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.annotation.StringRes


object ToastUtil {
    private var mAdapter: ToastAdapter? = null
    private var mToast: Toast? = null
    fun showToast(context: Context, msg: String?) {
        showToast(context, msg, Toast.LENGTH_SHORT)
    }

    @JvmOverloads
    fun showToast(context: Context, @StringRes resId: Int, duration: Int = Toast.LENGTH_SHORT) {
        showToast(context, context.resources.getText(resId), duration)
    }

    fun showToast(context: Context, msg: CharSequence?, duration: Int) {
        val b = mAdapter == null || mAdapter!!.displayable()
        if (!b) return
        if (Looper.getMainLooper() == Looper.myLooper()) obtainAndShowToast(context, msg, duration) else showToastOnUiThread(context, msg, duration)
    }

    fun cancelToast() {
        val b = mToast != null && (mAdapter == null || mAdapter!!.cancellable())
        if (!b) return
        mToast!!.cancel()
    }

    fun setToastAdapter(adapter: ToastAdapter?) {
        mAdapter = adapter
    }

    private fun showToastOnUiThread(context: Context, msg: CharSequence?, duration: Int) {
        Handler(Looper.getMainLooper()).post { obtainAndShowToast(context, msg, duration) }
    }

    @SuppressLint("ShowToast")
    private fun obtainAndShowToast(context: Context, msg: CharSequence?, duration: Int) {
        if (mToast == null) {
            mToast = Toast.makeText(context.applicationContext, msg, duration)
        } else {
            mToast!!.setText(msg)
            mToast!!.duration = duration
        }
        mToast!!.show()
    }

    interface ToastAdapter {
        fun displayable(): Boolean
        fun cancellable(): Boolean
    }
}